package com.thread.controller;

import com.sun.xml.internal.xsom.impl.ListSimpleTypeImpl;
import com.thread.mapper.CityMapper;
import com.thread.model.City;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Auther: 10070436
 * @Date: 2018/12/28 19:38
 * @Description: ZGS
 */
@RestController
@Slf4j
public class TestController {

    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    private static List<City> list = new ArrayList<>();

    private static CountDownLatch countDownLatch;

    @Autowired
    private CityMapper cityMapper;


    @PostConstruct
    public void init(){

        for (int i=0; i<10000; i++ ) {
            list.add(new City(null,"中国首都"+i,"北京"+i));
        }

    }



    @RequestMapping("/test/asyn")
    public String asyn() {

        long s = System.currentTimeMillis();


        try {
            //countDownLatch = new CountDownLatch(list.size());
            list.forEach( i -> {
                threadPoolTaskExecutor.execute(() -> {

                    cityMapper.insert(i);
                    //插入完成后减1
                    //countDownLatch.countDown();
                });

            } );
            //countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }

   /*     list.forEach( i -> {
            cityMapper.insert(i);
            //countDownLatch.countDown();
            //log.info(" 计数器....................... "+countDownLatch.getCount());
        } );
*/
/*

   list.parallelStream().forEach( i -> {
       cityMapper.insert(i);
   } );
*/

        System.out.println(System.currentTimeMillis() - s);

        return "success";
    }

}
